//引入formidable
const formidable = require('formidable');
const path = require('path');
//导入文章集合构造函数
const { Article } = require('../../model/article')


const articleAdd = (req, res) => {
  //1.创建表单解析对象
  const form = formidable({multiples: true});
  //2.配置上传文件的存放位置
  form.uploadDir = path.join(__dirname, '../', '../', 'public', 'uploads');
  //3.保存上传文件的后缀
  form.keepExtensions = true;
  //4.解析表单
  form.parse(req, async (err, fields, files) => {
    //err：表单解析失败的错误信息，解析成功err为空 fields：对象类型，普通表单数据 files:对象类型， 文件数据
    await Article.create({
      title: fields.title,
      author: fields.author,
      publishDate: fields.publishDate,
      cover: files.cover.path.split('public')[1],
      content: fields.content
    }).catch(err => res.status(400).send(err.message))

    res.status(200).send({
      meta: {
        msg: '添加文章成功！',
        status: 200
      }
    })
  })
}
module.exports = articleAdd






